<template>
  <view class="load_box">
    <div class="img_container">
      <div class="image_item" v-for="(image, index) in imageUrls" :key="index" @click="previewImage(index)">
        <img :src="image.img_url" alt="Image" class="image" />
      </div>
      <div class="image_item add_img" @click="upload">+</div>
    </div>
  </view>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue']);
const imageUrls = ref(props.modelValue);

watch(imageUrls, (newUrls) => {
  emit('update:modelValue', newUrls);
}, { deep: true });

const upload = async () => {
  try {
    const res = await uni.chooseImage({ count: 9 - imageUrls.value.length });
    uni.showLoading({ title: '上传中...' });
    for (const filePath of res.tempFilePaths) {
      const uploadRes = await uniCloud.uploadFile({
        filePath,
        cloudPath: `${Date.now()}-${res.tempFiles[0].name}`,
      });
      console.log(uploadRes, 'uploadRes')
      imageUrls.value.push({
        img_url: uploadRes.fileID,
      });
      await uniCloud.callFunction({
        name: 'addImage',
        data: {
          imageUrl: uploadRes.fileID,
          createTime: Date.now(),
        },
      });
    }
  } catch (e) {
    console.error('上传失败:', e);
  } finally {
    uni.hideLoading();
  }
};

const removeImage = (index) => {
  imageUrls.value.splice(index, 1);
};

const previewImage = (index) => {
  uni.previewImage({
    urls: imageUrls.value.map((item) => item.img_url),
    current: index,
    loop: true,
    indicator: 'number',
    longPressActions: {
      itemList: ['保存图片'],
      success: (res) => {
        console.log('success', res);
      },
      fail: (res) => {
        console.log('fail', res);
      },
    },
  });
};
</script>

<style scoped>
.load_box {
  display: flex;
  padding-top: 12rpx;
}

.img_container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  width: 100%;
  /* aspect-ratio: 1 / 1; */
}

.image_item {
  position: relative;
  overflow: hidden;
  aspect-ratio: 1 / 1;
  border-radius: 20rpx;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

.add_img {
  background-color: #f5f5f5;
  color: #999;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 100rpx;
  font-weight: 500;
  padding-bottom: 20rpx;
  box-sizing: border-box;
}
</style>
